<template>
  <Navbar title="详情" :right-txt="rightTxt" @rightClick="handleRightTxt" class="fixed w-full" />
  <div class="pt-[60px] px-[15px] text-[#333]">
    <van-skeleton v-if="loading" title :row="10" />
    <template v-else>
      <Name class="border-solid border-b border-[#e9e9e9]" :person="detail" />
      <van-form class="pb-8" ref="detailForm" @submit="handleSubmit">
        <div class="leading-[26px] text-sm">
          <van-field
            v-model="form.id_card"
            name="id_card"
            label="身份证号"
            placeholder="身份证号"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: idCardValidator, message: '请输入身份证号' }]"
          />
          <van-field
            type="tel"
            v-model="form.phone"
            name="phone"
            label="联系电话"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: requiredPhoneValidator, message: '请输入格式正确的联系电话' }]"
          />
          <!-- <van-field
            name="sex"
            label="性别"
            input-align="right"
            required
            :rules="[{ required: true, message: '请选择性别!' }]"
          >
            <template #input>
              <van-radio-group v-model="form.sex" direction="horizontal" :disabled="!isEdit">
                <van-radio v-for="item in sexList" :key="item.id" :name="item.label">{{
                  item.label
                }}</van-radio>
              </van-radio-group>
            </template>
          </van-field> -->
          <van-field
            v-model="form.isolate_reason"
            is-link
            readonly
            required
            name="isolate_reason"
            clearable
            input-align="right"
            label="人员类型"
            placeholder="人员类型"
            :disabled="!isEdit"
            @click="isEdit && (showReasonPicker = true)"
            :rules="[{ required: true, message: '请输入人员类型!' }]"
          />
          <van-popup v-model:show="showReasonPicker" position="bottom">
            <van-picker
              :columns="reasonList"
              value-key="name"
              @confirm="onReasonConfirm"
              @cancel="showReasonPicker = false"
            />
          </van-popup>
          <van-field
            v-model="form.person_category"
            is-link
            readonly
            required
            name="person_category"
            clearable
            label="人员分类"
            placeholder="人员分类"
            input-align="right"
            :disabled="!isEdit"
            @click="isEdit && (showCategoryPicker = true)"
            :rules="[{ required: true, message: '请输入人员分类!' }]"
          />
          <van-popup v-model:show="showCategoryPicker" position="bottom">
            <van-search v-model="searchCategory" placeholder="请输入搜索关键词" @update:model-value="onSearchCategory" />
            <van-picker
              ref="pickerCategory"
              :columns="personCategoryList"
              value-key="name"
              @confirm="onCategoryConfirm"
              @cancel="showCategoryPicker = false"
            />
          </van-popup>
          <van-field
            v-model="form.isolate_status"
            is-link
            readonly
            name="isolate_status"
            label="隔离状态"
            placeholder="隔离状态"
            input-align="right"
            :disabled="!isEdit"
            @click="isEdit && (showIsolateStatusPicker = true)"
            :rules="[{ required: true, message: '请选择隔离状态' }]"
          />
          <van-popup v-model:show="showIsolateStatusPicker" position="bottom">
            <van-picker
              :columns="isolate_status_list"
              value-key="label"
              @confirm="onIsolateStatusConfirm"
              @cancel="showIsolateStatusPicker = false"
            />
          </van-popup>
          <van-field
            v-model="form.community_id"
            is-link
            readonly
            required
            name="community_id"
            clearable
            label="社区"
            placeholder="社区"
            input-align="right"
            :disabled="!isEdit"
            @click="isEdit && (showCommunityPicker = true)"
            :rules="[{ required: true, message: '请选择社区!' }]"
          />
          <van-popup v-model:show="showCommunityPicker" position="bottom">
            <van-search
              v-model="search"
              placeholder="请输入搜索关键词"
              @update:model-value="onSearch"
            />
            <van-picker
              ref="picker"
              :columns="communityList"
              value-key="label"
              @confirm="onCommunityConfirm"
              @cancel="showCommunityPicker = false"
            />
          </van-popup>
          <van-field
            v-model="form.mch_id"
            is-link
            readonly
            required
            name="mch_id"
            label="小区"
            placeholder="小区"
            input-align="right"
            :disabled="!isEdit"
            @click="handleSelectChild"
            :rules="[{ required: true, message: '请选择小区!' }]"
          />
          <van-popup v-model:show="showCommunityChildPicker" position="bottom">
            <van-search
              v-model="search1"
              placeholder="请输入搜索关键词"
              @update:model-value="onSearch1"
            />
            <van-picker
              ref="picker1"
              :columns="communityChildList"
              value-key="label"
              @confirm="onCommunityChildConfirm"
              @cancel="showCommunityChildPicker = false"
            />
          </van-popup>
          <van-field
            v-model="form.address"
            name="address"
            label="现住址"
            placeholder="现住址"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ required: true, message: '请输入现住址' }]"
          />
          <van-field
            v-model="form.remark"
            name="remark"
            label="隔离原因"
            placeholder="隔离原因"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ required: true, message: '请输入隔离原因' }]"
          />
          <van-field
            v-model="form.dateRange"
            is-link
            type="text"
            required
            readonly
            name="dateRange"
            clearable
            label="隔离日期"
            placeholder="隔离日期"
            input-align="right"
            :disabled="!isEdit"
            @click="isEdit && (showCalendar = true)"
            :rules="[{ required: true, message: '请输入隔离日期!' }]"
          />
          <van-calendar
            v-model:show="showCalendar"
            :default-date="defaultDate"
            color="#2e7cff"
            type="range"
            @confirm="onCalendarConfirm"
          />
        </div>
        <h1 class="px-4 py-2">五包一责任人信息</h1>
        <div class="leading-[26px] text-sm">
          <van-field
            v-model="form.grid_name"
            name="grid_name"
            label="网格员"
            placeholder="网格员"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.grid_phone"
            name="grid_phone"
            type="tel"
            label="联系电话"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: phoneValidator, message: '请输入格式正确的联系电话' }]"
          />
          <van-field
            v-model="form.principal_name"
            name="principal_name"
            label="社区/村居/小区负责人"
            placeholder="社区/村居/小区负责人"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.principal_phone"
            name="principal_phone"
            type="tel"
            label="联系电话"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: phoneValidator, message: '请输入格式正确的联系电话' }]"
          />
          <van-field
            v-model="form.police_name"
            name="police_name"
            label="片警"
            placeholder="片警"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.police_phone"
            name="police_phone"
            label="联系电话"
            type="tel"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: phoneValidator, message: '请输入格式正确的联系电话' }]"
          />
          <van-field
            v-model="form.township_name"
            name="township_name"
            label="乡镇干部"
            placeholder="乡镇干部"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.township_phone"
            name="township_phone"
            label="联系电话"
            type="tel"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: phoneValidator, message: '请输入格式正确的联系电话' }]"
          />
          <van-field
            v-model="form.doctor_name"
            name="doctor_name"
            label="乡村社区医生"
            placeholder="乡村社区医生"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.doctor_phone"
            name="doctor_phone"
            label="联系电话"
            type="tel"
            placeholder="联系电话"
            input-align="right"
            :disabled="!isEdit"
            :rules="[{ validator: phoneValidator, message: '请输入格式正确的联系电话' }]"
          />
        </div>
        <h1 class="px-4 py-2">三级包联系人信息</h1>
        <div class="leading-[26px] text-sm">
          <van-field
            v-model="form.contractor_xian"
            name="contractor_xian"
            label="县级"
            placeholder="县级"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.contractor_xiang"
            name="contractor_xiang"
            label="乡级"
            placeholder="乡级"
            input-align="right"
            :disabled="!isEdit"
          />
          <van-field
            v-model="form.contractor_cun"
            name="contractor_cun"
            label="社区/村/小区"
            placeholder="社区/村/小区"
            input-align="right"
            :disabled="!isEdit"
          />
        </div>
      </van-form>
      <div v-if="!isEdit" class="flex justify-end pb-8">
        <template v-if="String(form.confirm_status) === '1' || String(form.confirm_status) === '3'">
          <a
            class="h-[25px] w-[72px] rounded-full border border-solid border-[#578fec] bg-[#e1ecff] text-[#578fec] active:bg-[#f1f5fd] text-sm flex justify-center items-center"
            @click="handleAccept"
            >确认接收</a
          >
          <a
            v-if="String(form.confirm_status) !== '3'"
            class="h-[25px] w-[72px] rounded-full border border-solid border-[#578fec] bg-[#e1ecff] text-[#578fec] active:bg-[#f1f5fd] text-sm flex justify-center items-center ml-1.5"
            @click="handleRejected"
            >驳回请求</a
          >
        </template>
        <template v-else>
          <a
            v-if="form.isolate_status === '1'"
            class="h-[25px] w-[72px] rounded-full border border-solid border-[#578fec] bg-[#e1ecff] text-[#578fec] active:bg-[#f1f5fd] text-sm flex justify-center items-center ml-1.5"
            @click="handleExtend"
            >延长隔离</a
          >
          <a
            v-if="form.isolate_status === '1'"
            class="h-[25px] w-[72px] rounded-full border border-solid border-[#578fec] bg-[#e1ecff] text-[#578fec] active:bg-[#f1f5fd] text-sm flex justify-center items-center ml-1.5"
            @click="handleRelieve"
            >解除隔离</a
          >
          <a
            v-if="form.isolate_status === '2'"
            class="h-[25px] w-[72px] rounded-full border border-solid border-[#578fec] bg-[#e1ecff] text-[#578fec] active:bg-[#f1f5fd] text-sm flex justify-center items-center ml-1.5"
            @click="handleHousehold"
            >居家隔离</a
          >
        </template>
      </div>
    </template>
  </div>
  <Accept :person="detail" />
  <Rejected :person="detail" />
  <Extend :person="detail" />
  <Household :person="detail" />
  <Relieve :person="detail" />
</template>

<script lang="ts">
  import { defineComponent, reactive, ref, toRefs, watch } from 'vue'
  import Navbar from '@/components/Navbar.vue'
  import Accept from '@/components/dialog/Accept.vue'
  import Rejected from '@/components/dialog/Rejected.vue'
  import Extend from '@/components/dialog/Extend.vue'
  import Household from '@/components/dialog/Household.vue'
  import Relieve from '@/components/dialog/Relieve.vue'
  import Name from './components/Name.vue'
  import { useGlobalEffect } from '@/hooks/useGlobalEffect'
  import { useDetailEffect } from './hooks/useDetailEffect'
  import { Notify, Toast } from 'vant'
  import { usePersonStore } from '@/store/person'

  export interface RightBtn {
    isEdit: boolean
    rightTxt: string
  }

  export default defineComponent({
    name: 'PersonDetail',
    components: {
      Navbar,
      Accept,
      Rejected,
      Extend,
      Household,
      Relieve,
      Name
    },
    setup() {
      const picker = ref()
      const picker1 = ref()
      const search = ref('')
      const search1 = ref('')
      const store = usePersonStore()

      const {
        getAllEnum,
        subcontractorList,
        reasonList,
        requiredPhoneValidator,
        phoneValidator,
        idCardValidator,
        solateStatusName,
        confirmStatusName
      } = useGlobalEffect()

      getAllEnum() // 获取枚举

      const {
        loading,
        detail,
        handleAccept,
        handleRejected,
        handleExtend,
        handleHousehold,
        communityList,
        showCommunityPicker,
        onCommunityConfirm,
        communityChildList,
        showCommunityChildPicker,
        onCommunityChildConfirm,
        showSubcontractorPicker,
        onSubcontractorConfirm,
        showReasonPicker,
        onReasonConfirm,
        showCalendar,
        onCalendarConfirm,
        isolate_status_list,
        showIsolateStatusPicker,
        onIsolateStatusConfirm,
        handleRelieve,
        query,
        id,
        sexList,
        form,
        showCategoryPicker,
        onCategoryConfirm,
        personCategoryList
      } = useDetailEffect()

      const handleSelectChild = () => {
        if (!rightBtn.isEdit) return
        if (communityChildList.value.length === 0) return Toast.fail('请先选择社区')
        showCommunityChildPicker.value = true
      }

      let defaultDate = ref([]) as any
      watch(
        () => detail.value,
        (newValue, oldValue) => {
          if (newValue) {
            const [minY, minM, minD] = (newValue.isolate_starttime as string).split('-') as any[]
            const [maxY, maxM, maxD] = (newValue.isolate_endtime as string).split('-') as any[]
            defaultDate.value = [new Date(minY, minM - 1, minD), new Date(maxY, maxM - 1, maxD)]
          }
        }
      )

      const detailForm = ref(null)
      // 右侧按钮
      const rightBtn = reactive<RightBtn>({
        rightTxt: '修改',
        isEdit: false
      })

      const handleRightTxt = async () => {
        if (rightBtn.isEdit === false) {
          rightBtn.isEdit = true
          rightBtn.rightTxt = '保存'
        } else {
          // 校验字段
          // 处理参数：form中有文字，query中有id
          ;(detailForm.value as any).submit()
        }
      }

      const handleSubmit = async () => {
        const params = { ...form.value, ...query }
        console.log(params)
        const ret = await store.updatePerson(params, id as string)
        if (ret === 200) {
          rightBtn.isEdit = false
          rightBtn.rightTxt = '修改'
          Notify({
            type: 'success',
            message: '更新成功',
            duration: 2000,
            onOpened: () => {
              location.reload()
            }
          })
        }
      }

      const pickerCategory = ref()
      const searchCategory = ref('')
      const onSearchCategory = (value: any) => {
        let filter = personCategoryList.value.filter((item) => {
          return item.name.indexOf(value) >= 0
        })
        pickerCategory.value.setColumnValues(0, filter)
      }

      const onSearch = (value: any) => {
        // 过滤结果
        let filter = communityList.filter((item) => {
          return item.label.indexOf(value) >= 0
        })
        picker.value.setColumnValues(0, filter)
      }

      const onSearch1 = (value: any) => {
        let filter = communityChildList.value.filter((item) => {
          return item.label.indexOf(value) >= 0
        })
        picker1.value.setColumnValues(0, filter)
      }

      return {
        picker,
        picker1,
        search,
        onSearch,
        search1,
        onSearch1,
        detailForm,
        detail,
        defaultDate,
        handleAccept,
        handleRejected,
        handleExtend,
        handleHousehold,
        handleRelieve,
        ...toRefs(rightBtn),
        handleRightTxt,
        communityList,
        showCommunityPicker,
        onCommunityConfirm,
        communityChildList,
        showCommunityChildPicker,
        onCommunityChildConfirm,
        showSubcontractorPicker,
        onSubcontractorConfirm,
        showReasonPicker,
        onReasonConfirm,
        showCalendar,
        onCalendarConfirm,
        subcontractorList,
        reasonList,
        personCategoryList,
        requiredPhoneValidator,
        phoneValidator,
        idCardValidator,
        solateStatusName,
        confirmStatusName,
        isolate_status_list,
        showIsolateStatusPicker,
        onIsolateStatusConfirm,
        handleSelectChild,
        handleSubmit,
        sexList,
        loading,
        form,
        showCategoryPicker,
        onCategoryConfirm,
        pickerCategory,
        searchCategory,
        onSearchCategory
      }
    }
  })
</script>
